<script setup>
import { ref,onMounted } from "vue";
import { useRouter,useRoute } from "vue-router";
import requestUtil from "@/utils/request.js";
import { ElMessage } from "element-plus";
import Cookies from "js-cookie";
let router = useRouter();
let route = useRoute();
let images = ref([]);
let comments = ref({
  userId: Cookies.get("userId"),
  content: "",
  selectedImages: [],
  value: 0
});
console.log(comments.value);

let fileInput = ref(null);
let storeId = ref(null);

// 获取店铺ID
const getStoreId = async () => {
  let res = await requestUtil.get("/app/getStoreId/", {
    orderId: route.query.orderId
  });
  if (res.data.code === 200) {
    storeId.value = res.data.storeId;
  }
};
const onClickRight = async () => {
  if (comments.value.value === 0 || comments.value.content.trim() === "") {
    ElMessage.warning("请填写完整信息");
    return;
  }

  const formData = new FormData();
  formData.append("commentInfo", JSON.stringify(comments.value)); // 将评论信息序列化为 JSON 字符串
  formData.append("userId", Cookies.get("userId")); // 用户 ID
  formData.append("storeId", storeId.value); // 店铺 ID

  // 添加多张图片
  images.value.forEach((imageFile, index) => {
    formData.append(`images_${index}`, imageFile); // 每张图片使用不同的 key
  });

  try {
    let res = await requestUtil.fileUpload("app/uploadComment/", formData);
    if (res.data.code === 200) {
      ElMessage.success("发布成功");
    }
  } catch (err) {
    ElMessage.error("发布失败");
  }
};

const selectImages = () => {
  // 触发文件输入元素的点击事件
  fileInput.value.click();
};
// 处理文件选择事件
const onFilesSelected = event => {
  const files = Array.from(event.target.files);
  files.forEach(file => {
    if (file.size > 2 * 1024 * 1024) {
      ElMessage.error(`文件 "${file.name}" 超过2MB，无法上传`);
    } else {
      images.value.push(file); // 存储文件对象
      const filePath = URL.createObjectURL(file);
      comments.value.selectedImages.push(filePath); // 用于预览
    }
  });
};
onMounted(() => {
  getStoreId();
});
const onClickLeft = () => {
  history.back();
};

const removeImage = () => {
  // 删除最后一张图片
  comments.value.selectedImages.pop();
  images.value.pop();
};
</script>

<template>
  <van-nav-bar
    title="动态发布"
    left-text="返回"
    left-arrow
    right-text="发布"
    @click-right="onClickRight"
    @click-left="onClickLeft"
  />
  <van-rate
    style="margin: 20px 20px;"
    v-model="comments.value"
    :size="25"
    color="#ffd21e"
    void-icon="star"
    void-color="#eee"
  />
  <div class="publish-updates">
    <div class="content">
      <div class="input-container">
        <textarea v-model="comments.content" placeholder="请输入动态内容"></textarea>
      </div>
      <div class="image-uploader">
        <!-- 隐藏的文件输入元素，允许选择多个文件 -->
        <input
          type="file"
          ref="fileInput"
          accept="image/*"
          multiple
          @change="onFilesSelected"
          style="display: none;"
        />
        <!-- 显示所选图片 -->
        <div v-if="comments.selectedImages.length > 0" class="selected-images">
          <img
            v-for="(image, index) in comments.selectedImages"
            :key="index"
            :src="image"
            class="selected-image"
            alt="Selected Image"
          />
          <button @click="removeImage()" class="remove-image">删除</button>
        </div>
        <div class="upload-tips">最多上传3张图片，每张图片大小不超过2M</div>
      </div>
      <div class="btn-selectImages">
        <!-- 自定义按钮 -->
        <button @click="selectImages" :disabled="comments.selectedImages.length >= 3">选择图片</button>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.publish-updates {
  width: 100%;
  display: flex;
  align-items: center;
  flex-direction: column;

  .header {
    width: 345px;
    margin-top: 46px;

    .title {
      float: left;
      font-weight: 500;
      font-size: 25px;
      color: #0a0615;
      margin: 0 0 0 115px;
    }

    .btn-publish {
      float: right;
      margin-top: 4px;
      font-size: 25px;
      color: #f25d29;
      border: none;
      border-radius: 5px;
      background-color: #ffffff;
      line-height: 25px;
    }
  }

  .content {
    padding: 30px;
    width: 100%;
    margin-top: 20px;
    margin-bottom: 40px;

    .input-container {
      width: 100%;
      height: 300px;

      textarea {
        resize: none;
        width: 100%;
        height: 100%;
        border: none;
        font-size: 25px;
        color: #0a0615;
        padding: 10px;
        border-radius: 5px;
        background-color: #f5f5f5;
      }
    }

    .image-uploader {
      width: 100%;
      height: 100px;
      margin-top: 20px;

      .selected-images {
        width: 100%;
        height: 100px;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
        margin-top: 10px;

        img {
          width: 80px;
          height: 80px;
          margin-right: 12px;
          object-fit: cover;
          border-radius: 5px;
        }

        button {
          display: flex;
          font-size: 30px;
          width: 50px;
          background-color: #ffc600;
          border: none;
          border-radius: 5px;
        }
      }

      .upload-tips {
        width: 100%;
        height: 20px;
        font-size: 30px;
        color: #999999;
        text-align: center;
        margin-top: 10px;
      }
    }

    .btn-selectImages {
      width: 100%;
      height: 40px;
      margin-top: 40px;
      display: flex;
      align-items: center;
      justify-content: center;

      button {
        width: 170px;
        margin-top: 50px;
        padding: 10px;
        border: none;
        font-size: 25px;
        color: #0a0615;
        background-color: #ffc400;
        background-repeat: no-repeat;
        background-position: center;
        border-radius: 20px;
      }
    }
  }
}
</style>